import execjs
import requests
import time

# 加载JavaScript代码
with open('x-tif-signature.js', 'r', encoding='utf-8') as f:
    x_tif_signature_js = f.read()

with open('ENC_DATA.js', 'r', encoding='utf-8') as f:
    enc_data_js = f.read()

with open('SIGN_DATA.js', 'r', encoding='utf-8') as f:
    sign_data_js = f.read()

# 编译JavaScript代码
ctx_x_tif_signature = execjs.compile(x_tif_signature_js)
ctx_enc_data = execjs.compile(enc_data_js)
ctx_sign_data = execjs.compile(sign_data_js)

# 定义请求参数
params = {
    "appCode": "T98HPCGN5ZVVQBS8LZQNOAEXVI9GYHKQ",
    "data": {
        "addr": "",
        "medinsLvCode": "",
        "medinsName": "",
        "medinsTypeCode": "",
        "outMedOpenFlag": "",
        "pageNum": 6,
        "pageSize": 10,
        "queryDataSource": "es",
        "regnCode": "410100",
    },
    "encType": "SM4",
    "signType": "SM2",
    "timestamp": int(time.time()),
    "version": "1.0.0"
}
# 生成加密参数
x_tif_signature = ctx_x_tif_signature.call('GET_X_TIF_SIGNATURE', params['timestamp'])
sign_data = ctx_sign_data.call('GET_SIGN_DATA', params)
enc_data = ctx_enc_data.call('GET_ENC_DATA', params)

# 设置请求头
cookies = {
    'yb_header_show': 'true',
    'yb_header_active': '-1',
}

headers = {
    'x-tif-signature': x_tif_signature,
    'x-tif-timestamp': str(params['timestamp']),
}
# 设置请求数据
json_data = {
    'data': {
        'data': {
            'encData': 'enc_data',
        },
        'appCode': params['appCode'],
        'version': params['version'],
        'encType': params['encType'],
        'signType': params['signType'],
        'timestamp': params['timestamp'],
        'signData': sign_data,
    },
}

# 发送请求
url = 'https://fuwu.nhsa.gov.cn/ebus/fuwu/api/nthl/api/CommQuery/queryFixedHospital'
response = requests.post(url, cookies=cookies, headers=headers, json=json_data)

# 打印响应
print(response.status_code)
print(response.json())
